<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 管理
 */
namespace app\settle\controller;

use  Mscore\Core\Controller;
use  app\settle\model\Duelorder as DuelorderModel;
use  app\settle\model\Common as CommonModel;
use  Mscore\Core\Lib\ArrayMethod;
use  app\admin\model\Login as LoginModel;

class DuelorderController extends Controller{

    private $model;
    private $login;
    private $error=['code'=>0,'msg'=>'fail'];
    private $success=['code'=>200,'msg'=>'success'];
    /**
     * 初始化自动连接方法
     * @param array $sysmod 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new DuelorderModel;
        $this->login = (new LoginModel)->isAuth();
        if(isset($this->login['code'])&&$this->login['code']==401){
            echo json_encode($this->login);
            Header("Location:".config('server.login_url'));
            exit;
        }

    }   

    /**
     * 列表
     * @param array $list 
     * @param array $where 
     */ 
    public function list(){
        $agent=(new CommonModel())->getAccountlist('grade="agent"','aid,username');
        $this->assign('agent', $agent);
        $this->display('list.html'); 
    }

    /**
     * 全部
     * @param array $all 
     * @param array $where 
     */ 
    public function all(){  
    //文章类
        $post = post();
        $page = post('page',1);
        $limit = post('limit',10);
        $where = ' a.dels<1 ';
        if($this->login['info']['ranges']<1){
            $where .= ' and a.pid = '.$this->login['info']['aid'].' or a.aid='.$this->login['info']['aid'];
        }
        if(post('username')){
                $aid=$this->model->userinfo('username="'.post('username').'"');
                $where .= ' and a.aid ='.$aid;
        }
        if(post('acode')){
            $where .= ' and a.sn like "%'.post('acode').'%"';
        }
        if(post('agent')){
            $where .= ' and a.pid ='.post('agent');
        }
        if(post('ortype')){
            $where .= ' and a.ortype ='.post('ortype');
        }
        if(post('time')){
            $time=post('time');
            switch ($time){
                case 1:
                    $where .= '';
                    break;
                case 2:
                    $where .= " and (a.createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59')) ";
                    break;
                case 3:
                    $where .= ' and (TO_DAYS(NOW()) - TO_DAYS(a.createtime) = 1)';
                    break;
                case 4:
                    $where .= ' and (WEEK(a.createtime) = WEEK(CURDATE()))';
                    break;
                case 5:
                    $where .= " and DATE_FORMAT(a.createtime,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')";
                    break;
                case 6:
                    $where .= " and (PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(a.createtime,'%Y%m')) = 1)";
                    break;
                default:
                    return $this->echojson($this->error);
                    break;
            }         
        }
        $datalist = $this->model->list($where,$page,$limit);
        $nowdraw = $this->model->suminfo($where,' sum(a.money) as money, sum(a.sx_fee) as fee');
        $win = $this->model->suminfo($where.' and ortype<2 and win=1',' sum(a.money) as money, sum(a.winmoney) as winmoney');
        $loss = $this->model->suminfo($where.' and ortype<2 and win=2',' sum(a.money) as money');
        $duel = $this->model->suminfo($where.' and ortype>1 ',' sum(a.money) as money, sum(a.winmoney) as winmoney');
        $nowdraw['money']=isset($nowdraw['money'])&&!empty($nowdraw['money'])?$nowdraw['money']:0;
        $nowdraw['fee']=isset($nowdraw['fee'])&&!empty($nowdraw['fee'])?$nowdraw['fee']:0;
        $nowdraw['win']=isset($win['money'])&&!empty($win['money'])&&isset($win['winmoney'])&&!empty($win['winmoney'])?$win['winmoney']-$win['money']:0;
        $nowdraw['loss']=isset($loss['money'])&&!empty($loss['money'])?$loss['money']:0;
        $nowdraw['duel']=isset($duel['money'])&&!empty($duel['money'])&&isset($duel['winmoney'])&&!empty($duel['winmoney'])?$duel['winmoney']-$duel['money']:0;
        $data = [
            "code" => 200,
            "data" => $datalist['datalist'],
            "count"=> $datalist['total'],
            "sum"=> $nowdraw,
            "msg" => 'ok'
        ];
        $this->echojson($data);
    }

    /**
     * 待定及确定
     * @param array $pending 
     * @param array $where 
     */ 
    public function pending(){  
        $post = post();
        $page = post('page',1);
        $limit = post('limit',10);
        $where = ' a.dels<1 and a.status=1';
        if($this->login['info']['ranges']<1){
            $where .= ' and a.pid = '.$this->login['info']['aid'].' or a.aid='.$this->login['info']['aid'];
        }
        if(post('title')){
                $where .= ' and a.title like "%'.post('title').'%"';
        }
        if(post('acode')){
            $where .= ' and a.acode like "%'.post('acode').'%"';
        }
        $datalist = $this->model->list($where,$page,$limit);
        $data = [
            "code" => 200,
            "data" => $datalist['datalist'],
            "count"=> $datalist['total'],
            "msg" => 'ok'
        ];
        $this->echojson($data);
    }

    /**
     * 审核
     * @param array $set 
     * @param array $where 
     */
    public function set(){ 
        $params = post();
        if($params){
            //post请求则保存
            $datainfo = $this->model->save($params);
            switch ($datainfo) {
                case true:
                    $this->echoJson($this->success);
                    break;
                default:
                    $this->echoJson($this->error);
                    break;
            }
        }else{
            $datainfo = $this->model->info(get('id'));
            // //定义变量datainfo输出
            $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';
            $datainfo['status']=isset($datainfo['status'])?$datainfo['status']:0;
       
            $this->assign('datainfo', $datainfo);
            $this->display('aedit.html');
        }
    }

    /**
     * 恢复
     * @param array $reset 
     * @param array $where 
     */
    public function reset(){ 
        $params = post();
        if($params){
            //post请求则保存
            $order = $this->model->info($params['id']);
            if(!isset($order['aid'])&&empty($order['aid'])) return $this->echoJson($this->error);
            $user=(new CommonModel())->getAccount('aid='.$order['aid'],['aid','amount','giftamount','pid']); //获取用户资金
            $pro = $this->model->daytraderisk('sn = "'.$order['sn'].'"',['id','win']);
            $win=!empty($params['win'])?$params['win']:0;
            switch (true) {
                case $win==0:
                    if(isset($pro['win'])&&!empty($pro['win'])){
                        switch ($pro['win']) {
                            case 1:
                                    $win = $order['updown']==2 ? 1:2;  //买跌赢，买涨亏
                                    break;
                            case 2:
                                    $win = $order['updown']==1 ? 1:2;  //买涨赢，买跌亏
                                break;
                        }
                    }else{
                        $chance=(new CommonModel())->getBaseinfo('keyname="chance"','content');
                        $chance=isset($chance['content']['win'])&&!empty($chance['content']['win'])?($chance['content']['win']/100):0.5;
                        if (probability($chance)) {
                            $win=1;
                        } else {
                            $win=2;
                        }
                    }
                    break;
                default:
                    // $win=$order['win'];
                    break;
            }
            $nowprice=$this->model->getprice($order['procode']);
            $rands=$this->model->random(['point_top'=>$nowprice['point_top'],'point_low'=>$nowprice['point_low']]);
            switch ($win) {
                case 1:
                    if($order['updown']==1){
                        $price= $nowprice['price']>$order['buyprice']?$nowprice['price']: round(($order['buyprice']+($rands*$nowprice['rands'])),$nowprice['length']);
                    }else{
                        $price= $nowprice['price']<$order['buyprice']?$nowprice['price']: round(($order['buyprice']-($rands*$nowprice['rands'])),$nowprice['length']);
                    }
                    break;
                case 2:
                    if($order['updown']==1){
                        $price= $nowprice['price']<$order['buyprice']?$nowprice['price']: round(($order['buyprice']-($rands*$nowprice['rands'])),$nowprice['length']);
                        }else{
                        $price= $nowprice['price']>$order['buyprice']?$nowprice['price']: round(($order['buyprice']+($rands*$nowprice['rands'])),$nowprice['length']);
                    }
                    break;
            }
            //返回数据
            $amount = $win==1 ? round(($order['money']*2-$order['sx_fee']),2) : 0 ;
            (new CommonModel())->startTrans();
            try {
                if($order['type']==1){
                    (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>($user['amount']+$amount)]);
                    $backamount=$user['amount']+$amount;
                }elseif($order['type']==2){
                    (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>($user['giftamount']+$amount)]);
                    $backamount=$user['giftamount']+$amount;
                }
                $this->model->updateOrder('id='.$order['id'],['status'=>2,'sellprice'=>$price,'win'=>$win]);
                if($order['id']){
                    $data=[
                        'backamount'=>$backamount,
                        'backmoney'=>$amount,
                        'win'=>$win,
                        'settletime'=>time()
                    ];
                    $this->model->updateorderlog($order['id'],$data);
                }
                (new CommonModel())->commit();
                return $this->echojson($this->success);
            } catch (Exception $e) {
                (new CommonModel())->rollback();
                return $this->echojson(Lang::get('Parerror'));
            }
        }else{
            $datainfo = $this->model->info(get('id'));
            // //定义变量datainfo输出
            $datainfo['id']=isset($datainfo['id'])?$datainfo['id']:'';
            $datainfo['win']=isset($datainfo['win'])?$datainfo['win']:0;
       
            $this->assign('datainfo', $datainfo);
            $this->display('reset.html');
        }
    }

    /**
     * 查看
     * @param array $show 
     * @param array $where 
     */
    public function show(){ 
        $datainfo = $this->model->info(get('id'));
        if(!empty($datainfo)){
            $datainfo['orderlog']=$this->model->infolog('orderid='.get('id'));
        }
        $this->assign('datainfo', $datainfo);
        $this->display('show.html');
    }  
}
